#!/usr/bin/php
<?php
// 只能以cli方式运行该脚本
if (php_sapi_name () != 'cli') {
	exit ();
}

define ( 'MODULE_NAME', 'home' ); // 模块名
define ( 'BASE_DIR', dirname ( __FILE__ ) . '/..' ); // 应用目录的路径
define ( 'APPLICATION_PATH', BASE_DIR . '/application' ); // 应用目录
define ( 'SYSTEM_PATH', BASE_DIR . '/system' ); // 框架目录
define ( 'VENDOR_PATH', BASE_DIR . '/vendor' ); // 第三方插件目录
define ( 'MODULE_PATH', APPLICATION_PATH . '/' . MODULE_NAME ); // 模块目录

$GLOBALS ['CONFIG'] = include SYSTEM_PATH . '/common/default_config.php';
require SYSTEM_PATH . '/Mikasa.php';

/**
 * 框架自带工具类
 */
class Tools {
	private $option;
	public function run() {
		fwrite ( STDOUT, "please select:\n" );
		fwrite ( STDOUT, "1:create table\n" );
		fwrite ( STDOUT, "2:drop table\n" );
		fwrite ( STDOUT, "3:startup job server\n" );
		fwrite ( STDOUT, "4:delete all data\n" );
		
		$this->option = fread ( STDIN, 1 );
		
		switch ($this->option) {
			case 1 :
				$this->createTable ();
				break;
			case 2 :
				$this->dropTable ();
				break;
			case 3 :
				$this->startJobServer ();
				break;
			case 4 :
				$this->deleteTable ();
				break;
			default :
				echo "nothing happend\n";
		}
	}
	/**
	 * 开启job server处理任务队列
	 */
	private function startJobServer() {
		$data = array (
				'send_mail' => 'sendMail',
				'log_sth' => 'LogSth' 
		);
		TaskQueue::run ( $data ); // 开始异步任务的处理
	}
	/**
	 * 建表
	 */
	private function createTable() {
		foreach ( $this->getModelsName () as $fileName ) {
			require (MODULE_PATH . '/models/' . $fileName);
			$segments = explode ( '.', $fileName );
			$className = "\\" . MODULE_NAME . "\\models\\" . $segments [0];
			$model = new $className ();
			$model->createTable ();
			echo 'create table ' . $model->getTableName (), "\n";
		}
	}
	/**
	 * 删表
	 */
	private function dropTable() {
		foreach ( $this->getModelsName () as $fileName ) {
			require (MODULE_PATH . '/models/' . $fileName);
			$segments = explode ( '.', $fileName );
			$className = "\\" . MODULE_NAME . "\\models\\" . $segments [0];
			$model = new $className ();
			$model->dropTable ();
			echo 'drop table ' . $model->getTableName (), "\n";
		}
	}
	/**
	 * 删出所有表的数据
	 */
	private function deleteTable() {
		foreach ( $this->getModelsName () as $fileName ) {
			require (MODULE_PATH . '/models/' . $fileName);
			$segments = explode ( '.', $fileName );
			$className = "\\" . MODULE_NAME . "\\models\\" . $segments [0];
			$model = new $className ();
			$model->delete ();
			echo 'delete table ' . $model->getTableName (), "\n";
		}
	}
	/**
	 * 获取所有model的名字
	 */
	private function getModelsName() {
		$dir = opendir ( MODULE_PATH . '/models' );
		$names = array ();
		while ( ($fileName = readdir ( $dir )) == true ) {
			if ($fileName == '.' || $fileName == '..') {
				continue;
			}
			$names [] = $fileName;
		}
		return $names;
	}
}

$tools = new Tools ();
$tools->run ();
